<template>
    <wd-notice-bar v-if="userProfile.shop?.status == 'refuse'" background-color="#FFEEF1" color="#F22447" :text="reason" />
    <view class="wai">
        <view class="logo">
            <view class="">店铺logo</view>
            <image v-if="!logoImg" @click="logo('logo')" class="logo1" src="@/static/scimg.png" mode=""></image>
            <image v-else @click="logo('logo')" class="logo1" :src="logoImg" mode=""></image>
        </view>
        <uni-section title="是否可清除已选项" type="line">
            <uni-data-select placeholder="请选择店铺分类" v-model="value" :localdata="range" @change="change" :clear="false"></uni-data-select>
        </uni-section>
        <view class="box-name">
            <view class="">店铺名称</view>
            <input v-model="parameter.name" class="input" placeholder="请输入" type="text" />
        </view>
        <view class="box-name">
            <view class="">店铺地址</view>
            <!-- <wd-col-picker v-model="address" :display-format="displayFormat" :columns="area" :column-change="columnChange" @confirm="handleConfirm"></wd-col-picker> -->
            <input @click="dizi" disabled v-model="address1" class="input" placeholder="请选择" type="text" />
        </view>
        <view class="box-name">
            <view class="">联系人姓名</view>
            <input v-model="parameter.contact" class="input2" placeholder="请输入" type="text" />
        </view>
        <view class="box-name">
            <view class="">联系电话</view>
            <input v-model="parameter.mobile" class="input" placeholder="请输入" type="text" />
        </view>
        <view class="box-name">
            <view class="">收款姓名</view>
            <input v-model="realName" class="input" placeholder="请输入收款真实姓名" type="text" />
        </view>
        <view class="box-name">
            <view class="">收款银行</view>
            <input v-model="bankName" class="input" placeholder="请输入银行姓名" type="text" />
        </view>
        <view class="box-name">
            <view class="">银行账号</view>
            <input v-model="bank" class="input" placeholder="请输入银行账号" type="text" />
        </view>
        <view class="Upload">上传营业执照</view>
        <image v-if="!license" @click="logo" class="license" src="@/static/scimg.png" mode=""></image>
        <image v-else @click="logo" class="license" :src="license" mode=""></image>
        <!-- 按钮 -->
        <view class="btn" @click="getBtn">提交</view>
    </view>
</template>

<script setup lang="ts">
import { uploadFile } from '@/utils/request.js';
import { apply, user, accountSave, category } from '@/api/index.js';
import { utils } from '@/utils/utils.js';
import { computed, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { useColPickerData } from '@/utils/citys.ts';
const { colPickerData, findChildrenByCode } = useColPickerData();
const address = ref<string[]>([]); //绑定地区的编号
const address1 = ref(''); //绑定地区的编号 选择地址11
const logoImg = ref(null); //店铺头像
const license = ref(null); //营业执照
const userProfile = ref({}); //存储用户信息
const realName = ref(null); //收款真实姓名
const bankName = ref(null); //银行姓名
const bank = ref(null); //银行账号
const range = ref([]); //分类列表
// 提交店铺参数
const parameter = ref({
    logo: null, //店铺头像
    name: null, //店铺名称
    address: null, //店铺地址
    mobile: null, //手机号
    contact: null, //联系人姓名
    category_id: null, //店铺分类
    lng: null, //经度
    lat: null, //纬度
    license: null //营业执照
});
onLoad(async () => {
    // await latAndlog(); //获取经纬度
    assortList();
});
onShow(() => {
    userInfo();
});

// 获取分类列表
const assortList = async () => {
    const ret = await category();
    console.log(ret);
    if (ret.code == 1) {
        range.value = ret.data.map((item) => ({
            ...item,
            text: item.name, // 将 name 的值赋给新的 text 属性
            value: item.id
        }));
    }
};
// 获取当前经纬度
const latAndlog = () => {
    return new Promise((resolve, reject) => {
        uni.getLocation({
            type: 'wgs84',
            success: function (res) {
                parameter.value.lng = res.longitude;
                parameter.value.lat = res.latitude;
                console.log('当前位置的经度：' + res.longitude);
                console.log('当前位置的纬度：' + res.latitude);
                resolve({ longitude: res.longitude, latitude: res.latitude });
            },
            fail: function (err) {
                reject(err);
            }
        });
    });
};
// 店铺审核失败显示失败信息
const reason = computed(() => {
    if (userProfile.value.shop.status == 'refuse') {
        return '审核失败：' + userProfile.value.shop.reason;
    }
});
// 获取用户信息
const userInfo = async () => {
    const ret = await user();
    if (ret.code == 1) {
        userProfile.value = ret.data;
        console.log('个人信息', userProfile.value);
    } else {
        utils('数据加载失败！');
    }
};
// 点击提交提交店铺资料
const getBtn = async () => {
    const errorMsg = check(parameter.value);
    // 提交前判断一下提交的信息
    if (errorMsg) {
        return utils(errorMsg);
    }
    editsave(); //提交信息
};

// 提交店铺资料
const realShop = async () => {
    const ret = await apply(parameter.value);
    console.log(ret);
    if (ret.code == 1) {
        uni.redirectTo({
            url: '/pages/sub/submit'
        });
    } else {
        utils(ret.msg);
    }
};
//选中分类的值
const change = (e) => {
    parameter.value.category_id = e;
};
// 保存银行信息
const editsave = async () => {
    const parms = ref({
        type: 'bank',
        account_name: realName.value,
        account_header: bankName.value,
        account_no: bank.value
    });
    const ret = await accountSave(parms.value);
    if (ret.code == 1) {
        realShop(); //店铺资料
    } else {
        utils(ret.msg);
    }
};
// 上传头像或营业执照
const logo = async (value: string) => {
    const ret = await uploadFile();
    if (value == 'logo') {
        logoImg.value = ret.data.fullurl;
        parameter.value.logo = ret.data.url;
    } else {
        license.value = ret.data.fullurl;
        parameter.value.license = ret.data.url;
    }
};
// 提交店铺认证前校验
const check = (param) => {
    if (param.logo == null || param.logo == '') {
        return '请上传店铺头像';
    } else if (param.name == null || param.name == '') {
        return '请输入店铺名称';
    } else if (param.address == null || param.address == '') {
        return '请选择店铺地址';
    } else if (param.contact == null || param.contact == '') {
        return '请输入联系人姓名';
    } else if (param.mobile == null || param.mobile.length !== 11) {
        return '请输入正确的手机号';
    } else if (realName.value == null || realName.value == '') {
        return '请输入收款真实姓名';
    } else if (bankName.value == null || bankName.value == '') {
        return '请输入银行姓名';
    } else if (bank.value == null || bank.value.length < 16) {
        return '请输入正确的银行卡号';
    } else if (param.license == null || param.license == '') {
        return '请上传营业执照';
    }
    return null; // 如果所有检查都通过，返回null表示无错误
};
// 选择店铺地址
const dizi = () => {
    uni.chooseLocation({
        success: function (res) {
            console.log(res);
            address1.value = res.address; //详细地址
            parameter.value.address = res.address;
            parameter.value.lng = res.longitude;
            parameter.value.lat = res.latitude;
        }
    });
};

// 选择地区  没用
// 初始化选项
const area = ref<any[]>([
    colPickerData.map((item) => {
        return {
            value: item.value,
            label: item.text
        };
    })
]);
// 选择后触发
const columnChange = ({ selectedItem, resolve, finish }) => {
    const areaData = findChildrenByCode(colPickerData, selectedItem.value);
    if (areaData && areaData.length) {
        resolve(
            areaData.map((item) => {
                return {
                    value: item.value,
                    label: item.text
                };
            })
        );
    } else {
        finish();
    }
};
// 格式化方法
const displayFormat = (selectedItems: Record<string, any>[]) => {
    // 使用 map 方法遍历数组，但注意最后一个元素的处理
    const formattedLabels = selectedItems.map((item, index, array) => {
        // 检查是否是最后一个元素
        if (index === array.length - 1) {
            // 如果是最后一个元素，则直接返回 label，不加 '-'
            return item.label;
        } else {
            // 否则，在 label 后添加 '-'
            return `${item.label}-`;
        }
    });
    // 使用 join 方法将数组元素拼接成一个字符串
    const resultString = formattedLabels.join('');
    parameter.value.address = resultString;
    // 返回（或打印）拼接后的字符串
    return resultString;
};
// 地址弹窗关闭触发
function handleConfirm(e) {
    console.log(e);
    // displayFormat(e.selectedItems);
}
</script>

<style lang="scss" scoped>
// 选择店铺地址样式
::v-deep .wd-col-picker__cell {
    width: 468rpx;
    padding: 0 !important;
    margin-left: 74rpx;
}
::v-deep .wd-col-picker__value--placeholder {
    color: #747474 !important;
    font-size: 35rpx;
}
::v-deep .wd-col-picker__arrow {
    display: none !important;
}
.wai {
    .license {
        width: 159rpx;
        height: 159rpx;
    }
    .btn {
        // position: fixed;
        // bottom: 20rpx;
        background-color: #f8bf5a;
        width: 670rpx;
        height: 100rpx;
        text-align: center;
        line-height: 100rpx;
        color: #fff;
        border-radius: 15rpx;
        margin-top: 100rpx;
    }
    .Upload {
        margin: 50rpx 0 38rpx 0;
    }
    .box-name {
        .input2 {
            flex: 1;
            margin-left: 46rpx;
			height: 100%;
        }
        .input {
            flex: 1;
            margin-left: 74rpx;
			height: 100%;
        }
        height: 126rpx;
        border-bottom: 2rpx solid #f7f7f7;
        display: flex;
        align-items: center;
    }
    .logo {
        .logo1 {
            width: 87rpx;
            height: 87rpx;
        }
        height: 168rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2rpx solid #f7f7f7;
    }
    padding: 0 40rpx;
    padding-bottom: 50rpx;
}
</style>
